//
//  ZLPullMenuContentView.swift
//  ZLPullMenuSwift
//
//  Created by 科大 on 2025/1/16.
//

import UIKit

// MARK: - ZLPullMenuContentViewDelegate

protocol ZLPullMenuContentViewDelegate: AnyObject {
    /// 即将选中回调
    func pullMenuContentViewWillSelected(_ indexPath: IndexPath) -> Bool
    
    /// 选中回调
    func pullMenuContentViewDidSelected(_ indexPath: IndexPath)
}

// MARK: - ZLPullMenuContentView

class ZLPullMenuContentView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    // MARK: - Properties
    
    /// 列表
    private lazy var collectionView: UICollectionView = {
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.showsHorizontalScrollIndicator = false
        cv.register(ZLPullMenuContentCell.self, forCellWithReuseIdentifier: "ZLPullMenuContentCell")
        cv.register(ZLPullMenuContentReusableView.self, 
                   forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, 
                   withReuseIdentifier: "ZLPullMenuContentReusableView")
        cv.delegate = self
        cv.dataSource = self
        cv.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 10, right: 10)
        return cv
    }()
    
    /// 布局
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.scrollDirection = .vertical
        return layout
    }()
    
    /// 数据源
    private var groups: [ZLPullMenuGroup] = []
    
    /// 代理
    weak var delegate: ZLPullMenuContentViewDelegate?
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Public Methods
    
    func getMenuHeight() -> CGFloat {
        var height: CGFloat = 0
        for group in groups {
            let line = group.options.count / 4
            var contentHeight = CGFloat(line * 10 + (line + 1) * 25)
            if group.options.count % 4 == 0 {
                contentHeight = CGFloat((line - 1) * 10 + line * 25)
            }
            height += 40 + contentHeight
        }
        return height + 10
    }
    
    func reloadData(_ groups: [ZLPullMenuGroup]) {
        self.groups = groups
        collectionView.reloadData()
    }
    
    // MARK: - UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return groups.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return groups[section].options.count
    }
    
    func collectionView(_ collectionView: UICollectionView, 
                       viewForSupplementaryElementOfKind kind: String, 
                       at indexPath: IndexPath) -> UICollectionReusableView {
        guard kind == UICollectionView.elementKindSectionHeader else { return UICollectionReusableView() }
        
        let reusableView = collectionView.dequeueReusableSupplementaryView(
            ofKind: UICollectionView.elementKindSectionHeader,
            withReuseIdentifier: "ZLPullMenuContentReusableView",
            for: indexPath) as! ZLPullMenuContentReusableView
        
        reusableView.group = groups[indexPath.section]
        return reusableView
    }
    
    func collectionView(_ collectionView: UICollectionView, 
                       cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: "ZLPullMenuContentCell",
            for: indexPath) as! ZLPullMenuContentCell
        
        let group = groups[indexPath.section]
        cell.option = group.options[indexPath.row]
        return cell
    }
    
    // MARK: - UICollectionViewDelegateFlowLayout
    
    func collectionView(_ collectionView: UICollectionView,
                       layout collectionViewLayout: UICollectionViewLayout,
                       referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: frame.width, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView,
                       layout collectionViewLayout: UICollectionViewLayout,
                       sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: (frame.width - 50) / 4, height: 25)
    }
    
    // MARK: - UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard delegate?.pullMenuContentViewWillSelected(indexPath) != false else { return }
        
        let group = groups[indexPath.section]
        let selectOption = group.options[indexPath.row]
        
        let selectedCount = group.options.filter { $0.selected }.count
        
        if selectOption.selected && group.mustSelect && selectedCount == 1 {
            print("必选不可取消")
            return
        }
        
        selectOption.selected.toggle()
        
        if !group.selecteds {
            group.options.forEach { option in
                if option !== selectOption {
                    option.selected = false
                }
            }
        }
        
        collectionView.reloadData()
        delegate?.pullMenuContentViewDidSelected(indexPath)
    }
}
